/*
 * 六瓜编程 2010-2020   @date: 2020-12-13 23:37:48
 * 描述：轮子走一个角度，走到了，通知上层。
 * author : XiaoShengYang    __lg_motor
*/

#include <lg_motor.h>

enum MOTOR_OFFSET {
    MOTOR_LEFT_OFT = 0,
    MOTOR_RIGHT_OFT,
};

#define MOTOR_MOTOR_NUM_MAX      2
#define MOTOR_FREQUENCY_DEFAULT  1000
#define MOTOR_DUTY_CYCLE_DEFAULT 50
#define MOTOR_DIR_DEFAULT        1
#define MOTOR_SPEED_MAX          100

struct motor_config {
    /* motor */
    lg_bool is_init;
    lg_u32 frequency;
    lg_u32 duty_cycle;

    /* wheel */
    lg_u8 dir;
    lg_u8 speed;
    lg_u8 go_time[MOTOR_MOTOR_NUM_MAX]; /* 每一个车轮转动时间 ms */
    motor_callback *callback;
};
static struct motor_config g_motor_config = {
    .is_init = lg_false,
    .frequency = MOTOR_FREQUENCY_DEFAULT,
    .duty_cycle = MOTOR_DUTY_CYCLE_DEFAULT,
    .dir = MOTOR_DIR_DEFAULT,
    .go_time = {0, 0},
    .callback = 0,
};

/* motor */
lg_void lg_motor_set_frequecy(enum wheel_offset wheel, lg_u32 frequecy)
{
}

lg_void lg_motor_set_duty_cycle(enum wheel_offset wheel, lg_u32 duty_cycle)
{
}

lg_bool lg_motor_init(lg_void)
{
    /* config attr */
    if (g_motor_config.is_init) {
        return lg_false;
    };
    lg_motor_set_frequecy(MOTOR_LEFT_OFT, g_motor_config.frequency);
    lg_motor_set_frequecy(MOTOR_RIGHT_OFT, g_motor_config.frequency);

    /* register callback */
    /* flag init */
    return g_motor_config.is_init = lg_true;
}

lg_bool lg_motor_deinit(lg_void)
{
    /* config attr */
    if (!g_motor_config.is_init) {
        return lg_false;
    }
    /* unregister callback */
    g_motor_config.callback = HI_NULL;
    /* flag init */
    g_motor_config.is_init = lg_false;
}

/* wheel */
lg_void lg_motor_wheel_set_dir(enum wheel_offset wheel, enum wheel_dir dir)
{
    if (dir >= DIR_NUM_MAX) {
        return;
    }
    if (g_motor_config.dir != dir) {
        g_motor_config.dir = dir;
    }
}

lg_void lg_motor_wheel_set_speed(enum wheel_offset wheel, lg_u32 speed)
{
    if (dir >= MOTOR_SPEED_MAX) {
        return;
    }
    if (g_motor_config.speed != speed) {
        g_motor_config.speed = speed;
    }
}

/* 注册回调函数 */
lg_u32 lg_motor_callback_register(motor_callback *callback)
{
    if (!callback) {
        return lg_false;
    }
    if (g_motor_config.callback != callback) {
        g_motor_config.callback = callback;
        return lg_true;
    }
}

static lg_bool ig_to_target(enum wheel_offset)
{
    return lg_true;
}

static lg_bool go_motor(enum wheel_offset)
{
    return lg_true;
}

/* 触发任务 
* 两个电机依次走各自设定好的位移（暂用走多长时间代替）,到位置发信号量（暂用回调函数代替）
*/
lg_void lg_motor_task_triger(hi_void)
{
    /* 到位置，执行上层回调 */
    lg_bool ret;
    ret = ig_to_target(WHEEL_LEFT);
    if (ret) {
        g_motor_config.callback();
    }
    ret = ig_to_target(WHEEL_RIGHT);
    if (ret) {
        g_motor_config.callback();
    }

    /* 执行motor运动到位置的过程 */
    go_motor(WHEEL_LEFT);
    go_motor(WHEEL_RIGHT);
}
